﻿using ERP.Common.Results;
using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 客户订单控制器---bpy
    /// </summary>
    public class CustomerOrderController : Controller
    {
        ICustomerOrderServices _customerOrderServices;

        public CustomerOrderController(ICustomerOrderServices customerOrderServices)
        {
            _customerOrderServices = customerOrderServices;
        }



        /// <summary>
        /// 客户订单列表页
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomerOrderQuery()
        {
            return View();
        }
        /// <summary>
        /// 新增客户订单
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomerOrderAdd()
        {
            return View();
        }

        /// <summary>
        /// 修改客户订单
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomerOrderEdit()
        {
            return View();
        }
        /// <summary>
        /// 产品列表下拉框
        /// </summary>
        /// <returns></returns>
        public IActionResult ProductInfoDilog()
        {
            return View();
        }

        /// <summary>
        /// 弹窗中的客户列表
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomerShowDilog()
        {
            return View();
        }

        /// <summary>
        /// 物料选择弹窗页面
        /// </summary>
        /// <returns></returns>
        public IActionResult MaterialSelectDialog()
        {
            return View();
        }

        /// <summary>
        /// 产品信息列表---bpy
        /// </summary>
        /// <param name="code">查询条件--产品编码</param>
        /// <param name="Name">查询条件--产品名称</param>
        /// <param name="page">分页--当前页</param>
        /// <param name="limit">分页--页容量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<ProductInfoRelationModel>> GetProductInfoRelation(string? code, string? Name, int page = 1, int limit = 10)
        {
            var i = await _customerOrderServices.GetProductInfoRelation(code, Name, page, limit);
            return i;
        }

        /// <summary>
        /// 物料产品列表API
        /// </summary>
        /// <param name="materielCode">物料编码</param>
        /// <param name="materielName">物料名称</param>
        /// <param name="page">当前页</param>
        /// <param name="limit">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<MaterialproductModel>> GetMaterialProductList(string? materielCode, string? materielName, int page = 1, int limit = 10)
        {
            return await _customerOrderServices.GetMaterialProductList(materielCode, materielName, page, limit);
        }

        /// <summary>
        /// 添加客户订单
        /// </summary>
        /// <param name="customerOrderDto">客户订单信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SimpleAPIResult> AddCustomerOrder([FromBody] CustomerOrderDto customerOrderDto)
        {
            try
            {
                // 检查DTO是否为空
                if (customerOrderDto == null)
                {
                    return new SimpleAPIResult
                    {
                        Success = false,
                        Code = EnumResult.创建失败,
                        Message = "订单信息不能为空",
                        Data = null
                    };
                }

                var orderId = await _customerOrderServices.AddCustomerOrder(customerOrderDto);
                return new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.创建成功,
                    Message = "订单添加成功",
                    Data = orderId
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.创建失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.创建失败,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 分页查询客户订单列表
        /// </summary>
        /// <param name="orderCode">订单编码</param>
        /// <param name="customerName">客户名称</param>
        /// <param name="productCode">产品编号</param>
        /// <param name="productName">产品名称</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="page">当前页</param>
        /// <param name="limit">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<CustomerOrderModel>> GetCustomerOrderList(
            string? orderCode = "",
            string? customerName = "",
            string? productCode = "",
            string? productName = "",
            int? orderStatus = null,
            string? startDate = "",
            string? endDate = "",
            int page = 1,
            int limit = 10)
        {
            var queryDto = new CustomerOrderQueryDto
            {
                OrderCode = orderCode,
                CustomerName = customerName,
                ProductCode = productCode,
                ProductName = productName,
                OrderStatus = orderStatus,
                StartDate = !string.IsNullOrEmpty(startDate) ? DateTime.Parse(startDate) : null,
                EndDate = !string.IsNullOrEmpty(endDate) ? DateTime.Parse(endDate) : null,
                Page = page,
                Limit = limit
            };

            return await _customerOrderServices.GetCustomerOrderList(queryDto);
        }

        /// <summary>
        /// 根据ID获取客户订单详情
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<SimpleAPIResult> GetCustomerOrderById(int id)
        {
            try
            {
                var order = await _customerOrderServices.GetCustomerOrderById(id);
                return new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.检索成功,
                    Message = "获取订单详情成功",
                    Data = order
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.检索失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 更新客户订单
        /// </summary>
        /// <param name="customerOrderDto">客户订单信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SimpleAPIResult> UpdateCustomerOrder([FromBody] CustomerOrderDto customerOrderDto)
        {
            try
            {
                if (customerOrderDto == null)
                {
                    return new SimpleAPIResult
                    {
                        Success = false,
                        Code = EnumResult.参数错误,
                        Message = "订单信息不能为空",
                        Data = null
                    };
                }

                var result = await _customerOrderServices.UpdateCustomerOrder(customerOrderDto);
                return new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.更新成功 : EnumResult.更新失败,
                    Message = result ? "订单更新成功" : "订单更新失败",
                    Data = result
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.更新失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取订单编号
        /// </summary>
        /// <param name="type">编号类型（如：KD-客户订单）</param>
        /// <returns></returns>
        [HttpGet]
        public SimpleAPIResult GetCode(string type = "")
        {
            try
            {
                if (string.IsNullOrEmpty(type))
                {
                    return new SimpleAPIResult
                    {
                        Success = false,
                        Code = EnumResult.参数错误,
                        Message = "编号类型不能为空",
                        Data = null
                    };
                }

                // 生成编号：类型前缀 + 当前日期(yyyyMMdd) + 雪花ID后6位
                var datePrefix = DateTime.Now.ToString("yyyyMMdd");
                var snowflakeId = YitIdHelper.NextId().ToString();
                var suffix = snowflakeId.Substring(snowflakeId.Length - 6);
                var code = $"{type}{datePrefix}{suffix}";

                return new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.成功,
                    Message = "编号生成成功",
                    Data = code
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"生成编号失败：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 批量删除客户订单
        /// </summary>
        /// <param name="ids">订单ID数组</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SimpleAPIResult> DeleteCustomerOrders([FromBody] int[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    return new SimpleAPIResult
                    {
                        Success = false,
                        Code = EnumResult.参数错误,
                        Message = "请选择要删除的订单",
                        Data = null
                    };
                }

                var result = await _customerOrderServices.DeleteCustomerOrders(ids);
                return new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.销毁成功 : EnumResult.销毁失败,
                    Message = result ? $"成功删除 {ids.Length} 条订单记录" : "删除订单失败",
                    Data = result
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.参数错误,
                    Message = ex.Message,
                    Data = null
                };
            }   
            catch (InvalidOperationException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.销毁失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 根据订单ID获取物料需求列表
        /// </summary>
        /// <param name="customerOrderId">客户订单ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<SimpleAPIResult> GetMaterialRequirementsByOrderId(int customerOrderId)
        {
            try
            {
                var materialRequirements = await _customerOrderServices.GetMaterialRequirementsByOrderId(customerOrderId);
                return new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.检索成功,
                    Message = "获取物料需求数据成功",
                    Data = materialRequirements
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.检索失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 更新客户订单和物料需求（带事务）
        /// </summary>
        /// <param name="requestData">包含订单信息和物料需求的请求数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SimpleAPIResult> UpdateCustomerOrderWithMaterialRequirements([FromBody] UpdateOrderWithMaterialsRequest requestData)
        {
            try
            {
                if (requestData == null || requestData.OrderInfo == null)
                {
                    return new SimpleAPIResult
                    {
                        Success = false,
                        Code = EnumResult.参数错误,
                        Message = "订单信息不能为空",
                        Data = null
                    };
                }

                var result = await _customerOrderServices.UpdateCustomerOrderWithMaterialRequirements(
                    requestData.OrderInfo, 
                    requestData.MaterialRequirements ?? new List<MaterialRequirementDto>());

                return new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.更新成功 : EnumResult.更新失败,
                    Message = result ? "订单和物料需求更新成功" : "订单和物料需求更新失败",
                    Data = result
                };
            }
            catch (ArgumentException ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.更新失败,
                    Message = ex.Message,
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.系统异常,
                    Message = $"系统错误：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}
